package org.bean.box.tcp;

import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;

@Slf4j
@Component
public class TcpHandler extends IoHandlerAdapter {

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        log.info("sessionCreated session : " + session.getId());
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        log.info("sessionOpened session : " + session.getId());
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        log.info("sessionClosed session : " + session.getId());
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        log.info("sessionIdle session : " + session.getId() + " status : " + status);
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        session.closeNow();
        log.info("exceptionCaught : " + cause.toString());
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        byte[] bytes = (byte[]) message;
        String msg = new String(bytes, Charset.forName("UTF-8"));
        log.info("messageReceived : " + msg);
        session.write(IoBuffer.wrap("R_OK".getBytes()));
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        log.info("messageSent");
    }

    @Override
    public void inputClosed(IoSession session) throws Exception {
        session.closeNow();
        log.info("inputClosed");
    }
}
